package awk.thread.future;

import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;

import java.util.concurrent.*;

@Slf4j
public class CompletableFutureTest2 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();

        CompletableFuture<Object> completableFuture3 = CompletableFuture.supplyAsync(CompletableFutureTest2::queryDate,executorService);

        completableFuture3.whenComplete((data,exception)->{
            if (data != null){
                System.out.println("正确完成输出结果 " + data);
            }
            if (exception != null){
                System.out.println("异常输出结果 " + exception.getMessage());
            }
        });
//        Object o = completableFuture3.get();
//        System.out.println("正确完成输出结果 " + o);

        System.out.println("task1");
        //completableFuture3.then()
        //线程池必须手动调用shutdown(),否则线程池会一直维护线程池的initNum个线程，这些线程都是非守护线程，
        //非守护线程一直存在，则主线程不会退出
       // executorService.shutdown();
    }

    public static JSONObject queryDate()  {
        JSONObject data = new JSONObject();
        data.put("name","anna");
        data.put("age",22);
        data.put("booked",false);
        try {
            Thread.sleep(9000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return data;
    }

    public static JSONObject queryDateWithException() throws Exception {
        JSONObject data = new JSONObject();
        data.put("name","anna");
        data.put("age",22);
        data.put("booked",false);
        throw new Exception("查询失败");
    }
}
